package sz.szsmk.citizencard.ui.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.alipay.sdk.app.AuthTask;
import com.chenenyu.router.Router;
import com.chenenyu.router.annotation.Route;
import com.king.keyboard.KingKeyboard;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

import org.greenrobot.eventbus.EventBus;

import java.util.Map;

import sz.szsmk.citizencard.DaggerApplication;
import sz.szsmk.citizencard.R;
import sz.szsmk.citizencard.model.network.bean.AuthResult;
import sz.szsmk.citizencard.databinding.LoginActivityBinding;
import sz.szsmk.citizencard.ioc.Compontent.DaggerCommonActivityComponent;
import sz.szsmk.citizencard.log.L;
import sz.szsmk.citizencard.model.network.bean.response.AuthorBean;
import sz.szsmk.citizencard.model.network.bean.response.CheckThirdAppUserRes;
import sz.szsmk.citizencard.model.network.bean.response.OauthTokenRes;
import sz.szsmk.citizencard.model.network.bean.response.UserBean;
import sz.szsmk.citizencard.model.network.dzbean.res.MessageEvent;
import sz.szsmk.citizencard.mvp.contract.ILoginContact;
import sz.szsmk.citizencard.mvp.presenter.ILoginPresenter;
import sz.szsmk.citizencard.ui.base.IBaseActivity;
import sz.szsmk.citizencard.util.ACache;
import sz.szsmk.citizencard.util.AndroidUtils;
import sz.szsmk.citizencard.util.Constant;
import sz.szsmk.citizencard.util.JumpThirdView;
import sz.szsmk.citizencard.util.JumpUtils;
import sz.szsmk.citizencard.util.PhoneFormatCheckUtils;
import sz.szsmk.citizencard.util.PubUtils;
import sz.szsmk.citizencard.util.SharedPreferencesTool;
import sz.szsmk.citizencard.util.StringUtils;
import sz.szsmk.citizencard.util.zxyh.CheckContentUtil;

/**
 * Copyright (c)2018
 * author: zdh
 * created on: 2018/5/22 15:32
 * description:
 */
@Route("login")
public class LoginActivity extends IBaseActivity<ILoginPresenter, LoginActivityBinding>
        implements ILoginContact.ILoginView, View.OnClickListener, TextWatcher {

    private ImageView iconQqlogin;
    private ImageView iconWxlogin;
    private ImageView iconAlilogin;

    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;
    private Button loginBtn;
    private TextView loginFogetPsd;
    private TextView loginRegitst;
    private EditText loginPwdEt;
    private EditText loginUserEt;
    private TextView tv_loginByMessage;
    private View inputLinear;
    private View belowLinear;
    private String userPsd;
    private String userPhone;
    private String androidId;

    private String loginType;
    public String uid;
    private boolean isAuthorLogin;
    private boolean isLogin;
    private CheckBox loginAgreement;
    private TextView loginRegisterAgreement;
    private TextView loginAuthAgreement;
   // private int loginCount=5;

    @Override
    protected int attachLayoutRes() {
        return R.layout.login_activity;
    }

    @Override
    protected void initInjector() {
        DaggerCommonActivityComponent.builder().appCompontent(DaggerApplication.getAppComponent())
                .build().inject(this);
    }
    private int stt;
    @Override
    protected void initViews() {
        //不能截屏
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
        androidId = AndroidUtils.getAndroidId(this);
        stt = getIntent().getIntExtra("stt",0);
        initKeyBoard();
        iconQqlogin = dataBinding.iconQqlogin;
        iconAlilogin = dataBinding.iconAlilogin;
        loginBtn = dataBinding.loginBtn;
        loginFogetPsd = dataBinding.loginFogetPsd;
        loginRegitst = dataBinding.loginRegitst;
        dataBinding.iconWxlogin.setOnClickListener(this);
        loginPwdEt = dataBinding.loginPwdEt;
        loginUserEt = dataBinding.loginUserEt;
        inputLinear = dataBinding.inputLayout;
        belowLinear = dataBinding.belowLayout;
        tv_loginByMessage = dataBinding.tvLoginByMessage;
        loginAgreement=dataBinding.loginAgreement;
        loginRegisterAgreement=dataBinding.loginRegisterAgreement;
        loginAuthAgreement=dataBinding.loginAuthAgreement;

        iconQqlogin.setOnClickListener(this);
        iconAlilogin.setOnClickListener(this);
        loginFogetPsd.setOnClickListener(this);
        loginRegitst.setOnClickListener(this);
        loginBtn.setOnClickListener(this);
        loginBtn.setOnClickListener(this);
        tv_loginByMessage.setOnClickListener(this);
        dataBinding.iconWblogin.setOnClickListener(this);
        dataBinding.loginRegisterAgreement.setOnClickListener(this);
        dataBinding.loginAuthAgreement.setOnClickListener(this);
        CheckContentUtil.checkContent(this,loginBtn,loginUserEt,loginPwdEt);
//      删除授权
        loginType = ACache.get(LoginActivity.this).getAsString("login_type");

        Intent intent = getIntent();
        isAuthorLogin = intent != null && intent.getExtras() != null &&
                intent.getExtras().getBoolean("authorizationLogin", false);
        String token = ACache.get(DaggerApplication.getIns()).getAsString("access_token");
        isLogin = !StringUtils.isEmpty(token);
        if (isAuthorLogin && isLogin) {
            inputLinear.setVisibility(View.GONE);
            loginBtn.setText("确认授权");
        }
        if (isAuthorLogin) {
            belowLinear.setVisibility(View.GONE);
        }

        loginUserEt.addTextChangedListener(this);

        loginPwdEt.addTextChangedListener(this);
        loginPwdEt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!PhoneFormatCheckUtils.isChinaPhone(loginUserEt.getText().toString())) {
                    loginUserEt.setError("手机号不规范，重新输入");
                }
            }
        });


        loginAgreement.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

            }
        });

    }
    private void initKeyBoard() {
        KingKeyboard kingKeyboard = new KingKeyboard(this,dataBinding.keyboardParent);
        //然后将EditText注册到KingKeyboard即可
        kingKeyboard.register(dataBinding.loginPwdEt,KingKeyboard.KeyboardType.NORMAL);


    }

    @Override
    protected void updateViews() {

    }

    @Override
    public void checkSuccessOrderStatusSucc() {

    }

    @Override
    public void checkSuccessOrderStatusFail() {

    }

    @Override
    public void updataError(String message) {
    }


    @Override
    public void loginFalie(UserBean loginResponse) {


        PubUtils.popTipOrWarn(this, loginResponse.getMessage());
        dismissLoadingDialog();
    }

    @Override
    public void loginError(String string) {
        PubUtils.popTipOrWarn(this, string);
        dismissLoadingDialog();
    }

    @Override
    public void authorSuccess(AuthorBean authorBean) {
        if ("0000".equals(authorBean.getCode())) {
            sendAuthorSuccessBoard(authorBean);
            finish();
        } else {
            PubUtils.popTipOrWarn(this, authorBean.getMsg());
        }
    }

    @Override
    public void authorFalie(AuthorBean authorBean) {
        PubUtils.popTipOrWarn(this, authorBean.getMsg());
        dismissLoadingDialog();
        finish();
    }

    @Override
    public void authorError(String string) {
        PubUtils.popTipOrWarn(this, string);
        dismissLoadingDialog();
        finish();
    }

    @Override
    public void checkThirdAppUserSucc(CheckThirdAppUserRes response, String i) {
        String checkStatus = response.getCheckStatus();
        //该QQ未绑定过账号
        if (checkStatus != null) {
            if (checkStatus.equals("0")) {
                Bundle bundle = new Bundle();
                bundle.putString("type", "qq");
                dismissLoadingDialog();
                JumpUtils.jumptoNatvie(LoginActivity.this, "getcode", 0, bundle);
            } else {
                //该用户已绑定过第三方账户直接登录
                String mUid = ACache.get(this).getAsString("uid");
                //                int type = Integer.parseInt(login_type);
                mPresenter.thirdAppLogin(Integer.parseInt(loginType), "", "", mUid);
            }
        } else {
            dismissLoadingDialog();
        }

    }

    @Override
    public void checkThirdAppUserFail() {
        dismissLoadingDialog();
    }

    @Override
    public void thirdAppLoginSucc() {
        dismissLoadingDialog();

        SHARE_MEDIA media = null;
        if (!TextUtils.isEmpty(loginType)) {
            if (loginType.equals("0"))
                media = SHARE_MEDIA.WEIXIN;
            else if (loginType.equals("1"))
                media = SHARE_MEDIA.QQ;
            else if (loginType.equals("2"))
                media = SHARE_MEDIA.SINA;
            else if (loginType.equals("3")){
                finish();
            }
            if (media == null)
                return;
            UMShareAPI.get(LoginActivity.this).deleteOauth(LoginActivity.this
                    , media, null);
        }

//        Router.build("main")
//                .go(this);
        finish();
    }

    @Override
    public void thirdAppLoginFail(String message) {
        dismissLoadingDialog();
    }


    @Override
    public void oauthTokenFail() {

    }

    @Override
    public void selectUserAuthFail() {

    }

    @Override
    public void selectUserAuthSucc() {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
        if (data == null)
            return;

        if (resultCode == 0) {
            String uid = data.getStringExtra("uid");
            String checkStatus = data.getStringExtra("checkStatus");

            L.e(Constant.TAG, "------------------------------login0");
        }

    }

    @Override
    public void updataSuccess(UserBean loginResponse) {
        dismissLoadingDialog();
        if (loginResponse.getCode().equals("000000")) {

            SharedPreferencesTool.saveBoolean(this, Constant.IS_REMBER_PSD, true);

            ACache.get(this).put("userPhone", userPhone);
            ACache.get(this).put("userPsd", userPsd);
            if(stt==1){
                finish();
            }else{
                EventBus.getDefault().post(MessageEvent.CODE_GESTURE_OPEN);
                Constant.EXTENT = "";
                if (isAuthorLogin) {
                    inputLinear.setVisibility(View.GONE);
                    loginBtn.setText("确认授权");
                    isLogin = true;
                } else {
                    finish();
//                    Router.build("main").go(this);
                }
            }

        } else {
            Toast.makeText(this, loginResponse.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.icon_qqlogin) {
            ACache.get(this).remove("login_type");
            loginType = 1 + "";
            ACache.get(this).put("login_type", loginType);
            Constant.is_third = true;
            authorization(SHARE_MEDIA.QQ);
        } else if (id == R.id.iconWxlogin) {
            ACache.get(this).remove("login_type");
            loginType = 0 + "";
            ACache.get(this).put("login_type", loginType);
            Constant.is_third = true;
            authorization(SHARE_MEDIA.WEIXIN);
        } else if (id == R.id.icon_wblogin) {
            Constant.is_third = true;
            ACache.get(this).remove("login_type");
            loginType = 2 + "";
            ACache.get(this).put("login_type", loginType);
            authorization(SHARE_MEDIA.SINA);
        } else if (id == R.id.bj_tv) {
        } else if (id == R.id.icon_alilogin) {
            Constant.is_third = true;
            mPresenter.oauthToken();
        } else if (id == R.id.login_btn) {
            if (isAuthorLogin && isLogin && loginAgreement.isChecked()) {
                mPresenter.author(ACache.get(DaggerApplication.getIns()).getAsString("access_token"));
            } else {
                userPsd = dataBinding.loginPwdEt.getText().toString();
                userPhone = dataBinding.loginUserEt.getText().toString();

                if (userPhone == null || userPhone.length() == 0 || userPhone.isEmpty()) {
                    Toast.makeText(this, "用户名不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (userPsd == null || userPsd.length() == 0 || userPsd.isEmpty()) {
                    Toast.makeText(this, "密码不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (!loginAgreement.isChecked()) {
                    Toast.makeText(this, "请先勾选隐私协议", Toast.LENGTH_SHORT).show();
                    return;
                }
                showLoadingDialog();
                mPresenter.login(userPsd, userPhone);
            }
        } else if (id == R.id.login_foget_psd) {
            Constant.is_third = false;
            Router.build("getcode")
                    .with("type", "forget")
                    .go(this);
        } else if (id == R.id.login_regitst) {
            Constant.is_third = false;
            ACache.get(this).remove("uid");
            ACache.get(this).remove("login_type");
            Router.build("getcode")
                    .with("type", "regitst")
                    .go(this);
        } else if (id == R.id.back) {
            if (isAuthorLogin) {
                Toast.makeText(this, "授权失败", Toast.LENGTH_LONG).show();
            }
            finish();
        } else if (id == R.id.tv_loginByMessage) {//短信登录
            Intent intent = new Intent(this, LoginByMessageActivity.class);
            startActivity(intent);
        } else if (id == R.id.login_register_agreement) {
            Bundle bundle = new Bundle();
            bundle.putString(Constant.TITLE, "");
            bundle.putString("url", "https://newapp.szsmk.com/app-front-end/#/common/serviceAgreement");
            JumpUtils.jumptoNatvie(this, "webView", 0, bundle);
        } else if (id == R.id.login_authAgreement) {
            Bundle bundle_login_authAgreement = new Bundle();
            bundle_login_authAgreement.putString(Constant.TITLE, "");
            bundle_login_authAgreement.putString("url", "http://newapp.szsmk.com/app-front-end/#/common/secretAgreement");
            JumpUtils.jumptoNatvie(this, "webView", 0, bundle_login_authAgreement);
        }
    }

    private void sendAuthorSuccessBoard(AuthorBean authorBean) {
        //通过Intent类的构造方法指定广播的ID
        Intent intent = new Intent("net.mobile.authorization.LOGIN");
        Bundle bundle = new Bundle();
        // 将要广播的数据添加到Intent对象中
        bundle.putString("authorBean", JSONObject.toJSONString(authorBean));
        intent.putExtras(bundle);
        intent.setFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
        // 发送广播
        sendBroadcast(intent);
    }

    public void authorization(SHARE_MEDIA share_media) {
        UMShareAPI.get(this).getPlatformInfo(this, share_media, new UMAuthListener() {
            @Override
            public void onStart(SHARE_MEDIA share_media) {
                L.e(Constant.TAG, "onStart " + "授权开始");
            }
            @Override
            public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
                L.e(Constant.TAG, "onComplete " + "授权完成");

                //sdk是6.4.4的,但是获取值的时候用的是6.2以前的(access_token)才能获取到值,未知原因
                String uid = map.get("uid");
                String openid = map.get("openid");//微博没有
                String unionid = map.get("unionid");//微博没有
                String access_token = map.get("access_token");
                String refresh_token = map.get("refresh_token");
                String expires_in = map.get("expires_in");
                String name = map.get("name");
                String gender = map.get("gender");
                String iconurl = map.get("iconurl");
                ACache.get(LoginActivity.this).remove("uid");
                ACache.get(LoginActivity.this).put("uid", uid);
                mPresenter.checkThirdAppUser(loginType + "", uid, androidId);
            }

            @Override
            public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
                L.e(Constant.TAG, "onError " + "授权失败");
            }

            @Override
            public void onCancel(SHARE_MEDIA share_media, int i) {
                L.e(Constant.TAG, "onCancel " + "授权取消");
            }
        });
    }


    @Override
    public void oauthTokenSucc(OauthTokenRes response) {
        if (response != null) {
            String authInfo = response.getSign();
            alipayLogin(authInfo);
        }
    }

    private void alipayLogin(final String authInfo) {

        Runnable authRunnable = new Runnable() {
            @Override
            public void run() {
                // 构造AuthTask 对象
                AuthTask authTask = new AuthTask(LoginActivity.this);
                // 调用授权接口，获取授权结果
                Map<String, String> result = authTask.authV2(authInfo, true);
//                Map<String, String> result = authTask.authV2(testInfo, true);

                Message msg = new Message();
                msg.what = SDK_AUTH_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread authThread = new Thread(authRunnable);
        authThread.start();
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {

                case SDK_AUTH_FLAG: {
                    showNoCancelLoadingDialog();
                    @SuppressWarnings("unchecked")
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();
                    String alipayOpenId = authResult.getAlipayOpenId();
                    String authCode = authResult.getAuthCode();
                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {

                        ACache.get(LoginActivity.this).remove("login_type");
                        uid = alipayOpenId;
                        loginType = 3 + "";
                        ACache.get(LoginActivity.this).put("login_type", loginType);
                        ACache.get(LoginActivity.this).put("uid", uid);

                        mPresenter.checkThirdAppUser(3 + "", alipayOpenId, androidId);
                    } else {
                        // 其他状态值则为授权失败
                        Toast.makeText(LoginActivity.this,
                                "授权失败" + String.format("authCode:%s", authResult.getAuthCode()), Toast.LENGTH_SHORT).show();
                        dismissLoadingDialog();
                    }
                    break;
                }
                default:
                    break;
            }
        }
    };

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void afterTextChanged(Editable editable) {
        CheckContentUtil.checkPhoneContent(this, loginBtn, loginUserEt, loginPwdEt);

    }
}
